<template>
  <div v-for="item in list" :key="item.id">
    <div class="title">
      <el-checkbox @change="checkAllChange(item)" v-model="item.checkAll" :indeterminate="item.indeterminate">{{
          item.name
      }}</el-checkbox>
    </div>
    <div class="group">
      <el-checkbox-group @change="groupChange(item)" v-model="item.checkedIds">
        <div class="item" v-for="child in item.children" :key="child.id">
          <el-checkbox :label="child.id">{{ child.name }}</el-checkbox>
        </div>
      </el-checkbox-group>
    </div>
  </div>
  <div class="save">
    <el-button type="primary" @click="save">保存</el-button>
    <el-button>清空</el-button>
  </div>
</template>
  
<script setup lang="ts">
import { user } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, toRefs } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();

const checkAllChange = (item: ICategory) => {
  item.checkedIds = item.checkAll ? item.children.map(child => child.id) : []
  item.indeterminate = !item.checkAll && item.checkedIds.length !== 0;
}

const groupChange = (item: ICategory) => {
  item.checkAll = item.checkedIds.length === item.children.length
  item.indeterminate = !item.checkAll && item.checkedIds.length !== 0;
}
type ICategory = IResourceCategoryModel & {
  children: IResourceModel[];
  checkedIds: number[];
  checkAll: boolean;
  indeterminate: boolean;
};

interface IState {
  list: ICategory[];
}


const state = reactive<IState>({
  list: [],
});


if (route.query.id) {
  // 保证两三个请求都要成功
  Promise.all([
    user.getAllResourceCategoryApi(),
    user.getAllResourceApi(),
    user.getListRoleResourceApio(parseInt(route.query.id as string)),
  ]).then(([res1, res2, res3]) => {
    // 请求成功了
    if (res1.code === 200 && res2.code === 200 && res3.code === 200) {
      //   分类
      state.list = res1.data.map((item) => ({
        ...item,
        children: [],
        checkedIds: [],
        checkAll: false,
        indeterminate: false
      }));
      res2.data.forEach((child) => {
        const p = state.list.find((p) => p.id === child.categoryId);
        p?.children.push(child);
      });
      state.list.forEach((item) => {
        res3.data.forEach((child) => {
          if (child.categoryId === item.id) {
            item.checkedIds.push(child.id);
          }
        });
      });
      state.list.forEach(item => {
        item.checkAll = item.checkedIds.length === item.children.length;
        item.indeterminate = !item.checkAll && item.checkedIds.length !== 0;
      })
    }
  });
}

const save = () => {
  ElMessageBox.confirm("确定要保存吗")
    .then(() => {
      // 发请求
      user
        .allocResourceApi({
          roleId: parseInt(route.query.id as string),
          // 这个参数就是 所有的 checkedIds 的总和  [1,2,3,4]
          resourceIds: state.list
            .map((item) => item.checkedIds)
            .reduce((prev, cur) => {
              return prev.concat(cur);
            }, []),
        })
        .then((res) => {
          ElMessage({
            message: res.message,
            type: res.code === 200 ? "success" : "error",
          });
        });
    })
    .catch(() => {});
};
const { list } = toRefs(state)
</script>
  
<style lang="less" scoped>
.title {
  padding: 10px;
  background-color: #f2f6fc;
}

.group {
  padding: 10px;

  .item {
    width: 33%;
  }
}
.save {
  display: flex;
  justify-content: center;
}
:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
}
</style>